package pdf.genPDF;

import com.itextpdf.commons.utils.Base64;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.layout.font.FontProvider;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.htmlconverter.LoadHtmlType;
import com.spire.pdf.htmlconverter.qt.Size;
import lombok.extern.slf4j.Slf4j;
import pdf.IText.ITextGenPDF;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zgj
 * @create 2022-12-30 11:54
 * pdf 生成类
 */
@Slf4j
public class GenPDF {
    /**
     * itextpdf 提供的 HTML String 转 PDF File
     * 效率较快
     * @param content html内容
     * @param outPath           输出pdf路径
     * @return 是否创建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
        } catch (Exception e) {
            System.out.println("生成模板内容失败" + e);
            return false;
        }
        return true;
    }

    /**
     * itextpdf 提供的 HTML String 转 PDF 字节数组
     * 效率较快
     * @param content html内容
     * @return PDF字节数组
     */
    public static byte[] html2Pdf(String content) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();;
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content,outputStream,converterProperties);
        } catch (Exception e) {
            System.out.println("生成 PDF 失败,{}"+e);
        }
        return outputStream.toByteArray();
    }


    /**
     *  spire.pdf.free-5.1.0.jar 提供的URL界面转pdf
     *  效率慢
     */
    @Deprecated
    public static void converterUrlToPDF() {
    	//指定URL路径
        String url = "https://www.likecs.com/show-165308.html#sc=200";

        //指定输出文档路径
        String fileName = "D:\\workspace\\projectBackUps\\work\\常州一院\\PdfTemplate\\UrlToPdf.pdf";

        //指定插件路径
        String pluginPath = "D:\\workspace\\projectBackUps\\work\\常州一院\\PdfTemplate\\plugins";

        //设置插件路径
        com.spire.pdf.htmlconverter.qt.HtmlConverter.setPluginPath(pluginPath);

        //将URL转换为PDF
        com.spire.pdf.htmlconverter.qt.HtmlConverter
        	.convert(url, fileName, true, 1000000, new Size(1200f, 1000f), new PdfMargins(0));
//        	.convert(url, fileName, true, 1000000, new Size(210, 297), new PdfMargins(5));
    }


    /**
     * spire.pdf.free-5.1.0.jar 提供的字符串转pdf
     * 效率慢
     * @param htmlString
     */
    @Deprecated
    public static void convterHtmlStringToPDF(String htmlString) {

        //指定输出文档路径
        String outputFile = "D:\\workspace\\projectBackUps\\work\\常州一院\\PdfTemplate\\UrlToPdf.pdf";

        //指定插件路径
        String pluginPath = "D:\\workspace\\projectBackUps\\work\\常州一院\\PdfTemplate\\plugins";

        //设置插件路径
        com.spire.pdf.htmlconverter.qt.HtmlConverter.setPluginPath(pluginPath);

        //将HTML字符串转换为PDF
        com.spire.pdf.htmlconverter.qt.HtmlConverter
        	.convert(htmlString, outputFile, true, 100000, new Size(700, 900), new PdfMargins(0), LoadHtmlType.Source_Code);
    }
    
    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
        paramMap.put("title", "门急诊病历");
        paramMap.put("patInfo", "门急诊病历asatInfopatInfopatInfopapatInfopatInfo" +
            "<br><br>" +
            "patInfopatInpatInfopatInfopatInfopatInfopat字符串InfopatInInfotInfopatInfoopatInf" +
            "fopatInfopatInfopatInfopatInfotInfopatInfo字符串patInfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfopa字符串tInfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfopa字符串tInfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfopat字符串InfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfopa字符串tInfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfop字符串atInfopatInfopatInfopatInfopatIn" +
            "fopatInfopatInfopatInfopatInfotInfopatInfofopa字符串tInfoppatInfopatInfopatInfopa" +
            "tInfopatInfopatInfopatInfopatIn字符串fopatInfotInfop字符串atInfoatInfo字符串pa字符串t");

        String base64 = getImgBase64();
        paramMap.put("signature", base64);
        String outPath = "D:\\workspace\\projectBackUps\\work\\常州一院\\PdfTemplate\\%FDF-a.pdf";
        System.out.println(outPath);
        ClassLoader classLoader = GenPDFHelper.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        String templateDirectory = resource.toURI().getPath();
System.out.println(templateDirectory);
        String templateContent = GenPDFHelper.getTemplateContent(templateDirectory, "test_template.html", paramMap);
//        System.out.println(templateContent);
//        GenPDF.html2Pdf(templateContent, outPath);

        byte[] pdf = ITextGenPDF.createPDF(templateContent);
        try {
            FileOutputStream outputStream  = new FileOutputStream(new File("D:/workspace/projectBackUps/work/常州一院/PdfTemplate/%FDF-b.pdf"));
            outputStream.write(pdf);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


//        converterUrlToPDF();
//        convterHtmlStringToPDF(templateContent);
        long endTime = System.currentTimeMillis();
        System.out.println("耗时：" + (endTime - startTime));
    }

    public static String getImgBase64() {
        String s1 = "0xFFD8FFE000104A46494600010101006000600000FFDB004300080606070605080707070909080A0C140D0C0B0B0C1912130F141D1A1F1E1D1A1C1C20242E2720222C231C1C2837292C30313434341F27393D38323C2E333432FFDB0043010909090C0B0C180D0D1832211C213232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232323232FFC0001108002D006D03012200021101031101FFC4001F0000010501010101010100000000000000000102030405060708090A0BFFC400B5100002010303020403050504040000017D01020300041105122131410613516107227114328191A1082342B1C11552D1F02433627282090A161718191A25262728292A3435363738393A434445464748494A535455565758595A636465666768696A737475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFC4001F0100030101010101010101010000000000000102030405060708090A0BFFC400B51100020102040403040705040400010277000102031104052131061241510761711322328108144291A1B1C109233352F0156272D10A162434E125F11718191A262728292A35363738393A434445464748494A535455565758595A636465666768696A737475767778797A82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2F3F4F5F6F7F8F9FAFFDA000C03010002110311003F00F7FA2938A334001E05666BDAC41E1FD0EF756BA57686D2132B88F1B881D8678CD6912315E07F107E12EB7E46B1AAD86A9A96AAD3DC07834F5C9203365B773CE3B605007AB784BC77A178CAC927D3AE56399B20DA4EE8275C7AA8278AE9C722BC9FE1A7C24D3342B4D2B5CD46DAE575E442EE9249F2C2C738F947700D7AB8200A007526D19CE39A6EE07F89697AD003A98CCB1AEE6E147534A7815E3BAD78F6E356F8B96FE0B4BBFECED2E293C9BAFDD65EF1987FAB1C1DAA738CF1EB9E9401EADA76A961AC5A0BAD3AEE0BAB72C50490B875C8382322AE02315C6F80BE1F5B780A1BD8AD751BABA8EE9C30497854C0EC077F535278DBC75A67856CCDBB335DEAD70BB2DB4FB76CCD23374E07207BFE5401D7641A7570BF0B349F13E91E1629E29BD9AE2EA693CC8E39E4323C2840F94B1EF9EDDABB81D28039FF0016EA9AF695A6C73787B441ABDD34A11E13308F62E0FCDCF5E6B9B8FC57F11AE6DFF75F0F638A618DC67D5230A7D703AD7A2E05181401C17DBFE285C6C1168BE1DB4CF2C6E2EE4931C74C28AC8F13DF78DBC3FA1C9AAEB7E2AD3B4EB48885234DD2CCD23B31C051E6363F1AF54E82B13C5BE59F08EACD35925EA2DA48C6DDD7225C2938A00F2CB1BAD135FB5B2B9BFF008B3AC86BB61E5DB2CF1DA3291C15755076FD7A7D6BAC1F07F4269BCC9F54F105C6E24B897516C3E7D71835E09F0C3C017DE2DF1159DC496B28D1A0983DCDC370ADB79D80F727A715F55EADADE9BA058B5EEAB7B15A5B2B60C92BE064F61EA7DA803CAA0FD9F34B3A9C97373AB5D0B5333325AC0300267E552CC49E9D6BD9946D5C5470CD15CC11CD048AF148A1D1D790C0F208A9BA50034F22B98F13EA9E1BF0742DE26D56DA249F7083ED315B0798E7A2EE1CF41DCD74E4802B99F1BF89F45F0B684D75ACA2DC2BB6C86D368669DFA850A7F9F6A00F1DF15FC7ED4AE2DFCAF0EE9AF60927DDBCBB50CE40FEEAFDDFE75E95F0D7C2D6765A159EB97BA6BAF882F53CDBAB9BC6F367C9E3EF1FBB91CE07AD61F837C323C49E219BC51E29B9B5B8D4AD5C2DB6930C9BD34BEEAACBD9FDBD7DFA763E20F887E16F0A5E2D9EAFAA2DBDC950FE5F97239DA7383F2A9F4A00EA80E296B8FB4F8A3E08BEBA8EDE0F115999643850FB9067EAC00AEB81DC33400EA28A4340087A578B7C62D13C471E8D71AF5CEB66E74DB5BB8DBFB2920DB0F925C63CCF9BE73BB6F5FD2BDA4F4ACCD7B4B875DF0F6A3A65C3C890DCC2F13B211B80C7519E334012E922D3FB26CDAC2D92DAD1A2578A1450A115867181C0EB543C57E15D3FC63A23E95A9197ECEEC1C3C4C03230E84120D269BA3DFD89D36D67D6659E1B280A9558563F3F00283275E80E70B819E6B78018A00F2FF0036A7E12F14DC780350BC5BEB68AD3ED9A7CF9C3247BB698D87E35EA0391544693A7C7AC36AAB6910D4258FC97B8DBF3941CEDCFA66AF0E94018DE29D797C35E1EBCD5BEC935DF909958615C9662703E8327935E5FF0FB43F13F8A7C69FF0009E78AAD238A0D84595BCCA77267EEB469FC207A9EBD7DEBDA7028C0A00F37F871E1EBBF0FF8B7C662E2CA78ADEEEF44F6B3C982B2A12E7823EB5D8F8865D22C348B8D4F56B48A7B7B38CCAFBA0129503AE01AD7C014854375A00F9BB53D760F8B1AE699A1E87E127B6D212EE37BBBA8A1512F979C124A8C2000FA9AFA3A08920812240022285504E4E00C77A7246918C22803D80A701401FFD9";
        String base64Data  = s1.substring(2);   // 去掉 0x
        String base64Head = "data:image/jpeg;base64,";

        byte[] data = s1.getBytes(StandardCharsets.UTF_8);

//        String text = Base64.encodeBytes(data);
//        System.out.println(text);
//        System.out.println(getElectronInfo(s1));
        return base64Head + Base64.encodeBytes(HexToByte(base64Data));
    }

    public static byte[] HexToByte(String hexString){
        int len = hexString.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                .digit(hexString.charAt(i + 1), 16));
        }
        return b;
    }
}
